<template>
  <div class="live-classroom">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="left-section">
        <el-icon class="icon"><VideoCamera /></el-icon>
        <span class="video-text">Video Call</span>
        <div class="divider"></div>
        <h1 class="title">{{ roomInfo.title }}</h1>
      </div>
      <div class="right-section">
        <div class="user-info">
          <div class="user-avatar">
            <img :src="userInfo.avatar" :alt="userInfo.name" />
          </div>
          <span class="name">{{ userInfo.name }}</span>
        </div>
      </div>
    </div>

    <!-- 提醒条 -->
    <div class="reminder-bar">
      <div class="reminder-content">
        <el-icon><Timer /></el-icon>
        <span class="time">{{ startTime }}</span>
        <span class="meeting-text">Meeting meeting</span>
      </div>
      <div class="online-count">
        <el-icon><User /></el-icon>
        <span>{{ students.length + 1 }} 人在线</span>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 主要内容区 -->
      <div class="main-content">
        <!-- 讲师/主画面 -->
        <div class="main-stream">
          <video ref="teacherVideo" :muted="true" autoplay></video>
          <div class="stream-info">
            <div class="user-info">
              <span class="name">{{ roomInfo.teacherName }}</span>
              <span class="status">主讲</span>
            </div>
          </div>
        </div>

        <!-- 右侧聊天面板 -->
        <div class="right-panel">
          <!-- 参会者列表 -->
          <div class="participants-section">
            <div class="section-header">
              <div class="title">成员 ({{ students.length + 1 }})</div>
            </div>
            <div class="participants-list">
              <!-- 老师 -->
              <div class="participant-item">
                <div class="video-container">
                  <video ref="teacherVideo1" autoplay></video>
                </div>
                <div class="participant-info">
                  <div class="name-with-status">
                    <span class="name">{{ roomInfo.teacherName }}</span>
                    <span class="status">主讲</span>
                  </div>
                </div>
              </div>

              <!-- 学生列表 -->
              <div
                v-for="student in students"
                :key="student.id"
                class="participant-item"
              >
                <div class="video-container">
                  <video
                    v-if="student.videoEnabled && student.hasCamera"
                    :ref="'student-' + student.id"
                    autoplay
                    :class="{ 'video-enabled': student.videoEnabled }"
                  ></video>
                  <div
                    v-else
                    class="placeholder"
                    :class="{ 'no-device': !student.hasCamera }"
                  >
                    <img :src="student.avatar" :alt="student.name" />
                    <span v-if="!student.hasCamera" class="no-device-text"
                      >未检测到摄像头</span
                    >
                  </div>
                </div>
                <div class="participant-info">
                  <div class="name-with-status">
                    <span class="name">{{ student.name }}</span>
                    <div
                      class="mic-status"
                      :class="{ 'mic-off': !student.audioEnabled }"
                    >
                      <el-icon :size="14">
                        <component
                          :is="student.audioEnabled ? 'Microphone' : 'Mute'"
                        />
                      </el-icon>
                      <div class="volume-indicator" v-if="student.isSpeaking">
                        <span></span>
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 聊天区域 -->
          <div class="chat-section">
            <div class="section-header">
              <div class="title">聊天</div>
            </div>
            <div class="messages" ref="messageContainer">
              <div
                v-for="msg in messages"
                :key="msg.id"
                class="message-item"
                :class="{
                  'message-self': msg.sender === '我',
                  'message-teacher': msg.isTeacher,
                }"
              >
                <div class="message-content">
                  <span class="sender-name">
                    {{ msg.isTeacher ? `${msg.sender}(老师)` : msg.sender }}
                  </span>
                  <div class="message-text">{{ msg.content }}</div>
                </div>
              </div>
            </div>
            <div class="input-area">
              <input
                v-model="newMessage"
                @keyup.enter="sendMessage"
                placeholder="发送消息..."
              />
              <button @click="sendMessage">
                <el-icon><Position /></el-icon>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { VideoCamera, Timer, Position, User } from "@element-plus/icons-vue";
import LANWebRTCConnection from "@/utils/LANWebRTCConnection";

const teacherVideo = ref(null);
const messageContainer = ref(null);
const newMessage = ref("");

// 生成随机头像的函数
const getRandomAvatar = (seed) => {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`;
};

// 房间信息
const roomInfo = ref({
  id: "room123",
  title: "高级JavaScript编程实战课程",
  teacherName: "张老师",
  teacherAvatar: getRandomAvatar("teacher"),
});

// 开始时间
const startTime = ref("00:00:00");

// 聊天消息
const messages = ref([
  {
    id: 1,
    sender: "张老师",
    content: "欢迎同学们来到课堂！",
    isTeacher: true,
  },
  {
    id: 2,
    sender: "学生1",
    content: "老师好！",
    isTeacher: false,
  },
  {
    id: 3,
    sender: "张老师",
    content: "今天我们来讲解JavaScript的高级特性",
    isTeacher: true,
  },
]);

// 学生列表
const students = ref([
  {
    id: 1,
    name: "学生1",
    audioEnabled: false,
    videoEnabled: false,
    avatar: getRandomAvatar("student1"),
    hasCamera: true,
    hasMicrophone: true,
    isSpeaking: false,
  },
  {
    id: 2,
    name: "学生2",
    audioEnabled: true,
    videoEnabled: true,
    avatar: getRandomAvatar("student2"),
    hasCamera: true,
    hasMicrophone: true,
  },
  {
    id: 3,
    name: "学生3",
    audioEnabled: false,
    videoEnabled: false,
    avatar: getRandomAvatar("student3"),
    hasCamera: false,
    hasMicrophone: true,
  },
]);

// 添加用户信息
const userInfo = ref({
  name: "张三",
  avatar: getRandomAvatar("current-student"),
});

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim()) {
    messages.value.push({
      id: Date.now(),
      sender: "我",
      content: newMessage.value,
      isTeacher: false,
    });
    newMessage.value = "";
    // 滚动到最新消息
    setTimeout(() => {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }, 0);
  }
};

// 更新课程时间
const updateTime = () => {
  const now = new Date();
  startTime.value = now.toLocaleTimeString("en-US", {
    hour12: false,
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

const peerCon = ref(null);

// 或者方法2：使用 UUID v4
const generateUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};
// 加入直播
const joinLive = async () => {
  const peerId = generateUUID();
  peerCon.value.peerId = peerId;
  // 加入直播逻辑
  await peerCon.value.createPeerConnection(peerId, 0);
  peerCon.value.peerConnection.ontrack = (event) => {
    console.log(
      "🚀 ~ initializePeerConnection ~ event:",
      event.streams[0],
      teacherVideo.value
    );
    teacherVideo.value.srcObject = event.streams[0];
  };
  peerCon.value.getBroadcastChannel().postMessage({
    type: "join",
    data: {
      peerId,
    },
  });
};

onMounted(() => {
  // 开始计时
  const timer = setInterval(updateTime, 1000);
  peerCon.value = new LANWebRTCConnection();
  joinLive();
  onUnmounted(() => clearInterval(timer));
});
</script>

<style lang="scss" scoped>
.live-classroom {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #0a0b1a;
  color: #fff;

  .header {
    height: 60px;
    background: #14152b;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .left-section {
      display: flex;
      align-items: center;
      gap: 12px;

      .video-text {
        font-weight: 500;
      }

      .divider {
        width: 1px;
        height: 24px;
        background: rgba(255, 255, 255, 0.2);
      }

      .title {
        font-size: 16px;
        color: rgba(255, 255, 255, 0.9);
      }
    }

    .right-section {
      display: flex;
      align-items: center;
      gap: 20px;

      .user-info {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 6px;
        border-radius: 30px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background: rgba(255, 255, 255, 0.15);
        }

        .user-avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .name {
          padding: 0 8px 0 0;
          font-size: 14px;
          color: #fff;
        }
      }
    }
  }

  .reminder-bar {
    background: #1e1f3a;
    padding: 12px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    .reminder-content {
      display: flex;
      align-items: center;
      gap: 12px;
      color: #4080ff;

      .time {
        font-weight: 500;
      }
    }

    .online-count {
      color: #4080ff;
      display: flex;
      align-items: center;
      gap: 6px;
    }
  }

  .content-wrapper {
    flex: 1;
    display: flex;
    overflow: hidden;

    .main-content {
      flex: 1;
      display: flex;
      height: calc(100vh - 108px);

      .main-stream {
        flex: 1;
        position: relative;
        background: #000;
        border-radius: 8px;
        overflow: hidden;

        video {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .stream-info {
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          padding: 10px 24px;
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          box-sizing: border-box;
          background: linear-gradient(
            to top,
            rgba(0, 0, 0, 0.8),
            rgba(0, 0, 0, 0)
          );

          .user-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .name {
              font-size: 16px;
              color: #fff;
              font-weight: 500;
            }

            .status {
              padding: 2px 8px;
              background: rgba(64, 128, 255, 0.2);
              border: 1px solid rgba(64, 128, 255, 0.4);
              color: #4080ff;
              font-size: 12px;
              border-radius: 4px;
            }
          }
        }
      }

      .right-panel {
        width: 300px;
        background: #1e1f3a;
        border-left: 1px solid rgba(255, 255, 255, 0.1);
        display: flex;
        flex-direction: column;

        .participants-section {
          flex: 1;
          display: flex;
          flex-direction: column;
          min-height: 0;
          .section-header {
            padding: 12px 16px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
          }

          .participants-list {
            flex: 1;
            overflow-y: auto;
            padding: 8px;

            // 滚动条样式
            &::-webkit-scrollbar {
              width: 6px;
            }

            &::-webkit-scrollbar-track {
              background: transparent;
            }

            &::-webkit-scrollbar-thumb {
              background: rgba(255, 255, 255, 0.2);
              border-radius: 3px;

              &:hover {
                background: rgba(255, 255, 255, 0.3);
              }
            }

            &:hover::-webkit-scrollbar-thumb {
              background: rgba(255, 255, 255, 0.2);
            }

            &:not(:hover)::-webkit-scrollbar-thumb {
              background: transparent;
            }

            .participant-item {
              margin-bottom: 12px;
              background: #2b2b2b;
              border-radius: 8px;
              overflow: hidden;

              .video-container {
                width: 100%;
                aspect-ratio: 16/9;
                background: #1a1a1a;
                position: relative;

                video {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }

                .placeholder {
                  width: 100%;
                  height: 100%;
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  background: #1a1a1a;

                  img {
                    width: 60px;
                    height: 60px;
                    border-radius: 50%;
                    object-fit: cover;
                  }

                  .no-device-text {
                    margin-top: 8px;
                    font-size: 12px;
                    color: rgba(255, 255, 255, 0.5);
                  }
                }
              }

              .participant-info {
                padding: 8px 12px;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .name-with-status {
                  display: flex;
                  align-items: center;
                  gap: 8px;

                  .name {
                    font-size: 14px;
                    color: #fff;
                    font-weight: 500;
                  }

                  .status {
                    padding: 2px 8px;
                    background: rgba(64, 128, 255, 0.2);
                    border: 1px solid rgba(64, 128, 255, 0.4);
                    color: #4080ff;
                    font-size: 12px;
                    border-radius: 4px;
                  }

                  .mic-status {
                    display: flex;
                    align-items: center;
                    gap: 4px;

                    .el-icon {
                      font-size: 14px;
                      color: #4080ff;

                      &.is-muted {
                        color: #ff4d4f;
                      }
                    }

                    .volume-indicator {
                      display: flex;
                      align-items: flex-end;
                      gap: 2px;
                      height: 12px;

                      span {
                        width: 2px;
                        background: #4080ff;
                        border-radius: 1px;
                        animation: volume-wave 1s ease-in-out infinite;

                        &:nth-child(1) {
                          height: 4px;
                          animation-delay: 0s;
                        }
                        &:nth-child(2) {
                          height: 6px;
                          animation-delay: 0.2s;
                        }
                        &:nth-child(3) {
                          height: 8px;
                          animation-delay: 0.4s;
                        }
                        &:nth-child(4) {
                          height: 6px;
                          animation-delay: 0.6s;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        .chat-section {
          flex: 1;
          display: flex;
          flex-direction: column;

          .section-header {
            padding: 12px 16px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);

            .title {
              font-size: 14px;
              color: rgba(255, 255, 255, 0.9);
              font-weight: 500;
            }
          }

          .messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px;

            // 滚动条样式
            &::-webkit-scrollbar {
              width: 6px;
            }

            &::-webkit-scrollbar-track {
              background: transparent;
            }

            &::-webkit-scrollbar-thumb {
              background: rgba(255, 255, 255, 0.2);
              border-radius: 3px;

              &:hover {
                background: rgba(255, 255, 255, 0.3);
              }
            }

            &:hover::-webkit-scrollbar-thumb {
              background: rgba(255, 255, 255, 0.2);
            }

            &:not(:hover)::-webkit-scrollbar-thumb {
              background: transparent;
            }

            .message-item {
              margin-bottom: 12px;

              .message-content {
                .sender-name {
                  display: block;
                  color: rgba(255, 255, 255, 0.6);
                  font-size: 12px;
                  margin-bottom: 4px;
                }

                .message-text {
                  color: #fff;
                  font-size: 14px;
                  line-height: 1.4;
                  padding: 8px 12px;
                  background: rgba(255, 255, 255, 0.1);
                  border-radius: 4px;
                  word-break: break-word;
                  display: inline-block;
                  max-width: 80%;
                }
              }

              // 老师的消息样式
              &.message-teacher {
                .message-content {
                  .sender-name {
                    color: #4080ff;
                    font-weight: 500;
                  }

                  .message-text {
                    background: rgba(64, 128, 255, 0.15);
                    border: 1px solid rgba(64, 128, 255, 0.2);
                  }
                }
              }

              // 自己发送的消息样式
              &.message-self {
                .message-content {
                  text-align: right;

                  .sender-name {
                    color: rgba(255, 255, 255, 0.6);
                  }

                  .message-text {
                    background: #4080ff;
                    color: #fff;
                    border-radius: 4px;
                    text-align: left;
                  }
                }
              }
            }
          }

          .input-area {
            padding: 12px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            gap: 8px;

            input {
              flex: 1;
              background: #2b2b2b;
              border: 1px solid rgba(255, 255, 255, 0.1);
              border-radius: 4px;
              padding: 8px 12px;
              color: #fff;
              outline: none;

              &::placeholder {
                color: rgba(255, 255, 255, 0.3);
              }

              &:focus {
                border-color: #4080ff;
              }
            }

            button {
              width: 36px;
              height: 36px;
              padding: 0;
              display: flex;
              align-items: center;
              justify-content: center;
              background: #4080ff;
              color: #fff;
              border: none;
              border-radius: 4px;
              cursor: pointer;
              transition: all 0.3s;

              .el-icon {
                font-size: 18px;
              }

              &:hover {
                background: #5090ff;
              }

              &:active {
                transform: scale(0.95);
              }
            }
          }
        }
      }
    }
  }
}
</style>
